﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.MenuCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.MenuHandler
{
    /// <summary>
    /// 菜单添加
    /// </summary>
    public class AddMenuHandler : IRequestHandler<AddMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        public AddMenuHandler(IBaseRepository<Menu> menuRep, IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            try
            {
                var model = mapper.Map<Menu>(request);
                model.CreateTime = DateTime.Now;
                model.IsDeleted = false;
                var s=menuRep.AddAsync(model).Result;
                if (s > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = s;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    result.Data = s;
                }
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
